<?php
/**
 * 芦美广告公众号 微信网页授权API
 * ==访问本页的URL示例==
 * http://bid999.com/api/oauth2/sh_lumei/get_userinfo.php?url=abc.com,
 *
 * ==重定向的URL示例==
 * http://abc.com/?u=(序列化之后的用户信息)
 *
 */

//应用ID
$appid = 'wx75d7dc5f9c92e40f';

//应用密钥
$secret = '488cc5a8b13d27c0b110c9756f5ca941';

//PHP GET请求
function http_get($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url );
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
    $tmpInfo = curl_exec($curl);
    return $tmpInfo;
}

if(!isset($_GET['code'])){
    $scope = 'snsapi_userinfo';
    $state = $_GET['url'] ? urlencode($_GET['url']) : "http://bid999.com/api/oauth2/sh_lumei/demo/userinfo.php";
    $redirectUri = urlencode('http://bid999.com/api/oauth2/sh_lumei/get_userinfo.php');
    $wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirectUri.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
    header('Location:'.$wxUrl);
}else{
    $code = $_GET['code'];
    $state = $_GET['state'];
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
    $res = json_decode(http_get($url));
    $access_token = $res->access_token;
    $openid = $res->openid;
    $userinfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
    $userinfo = serialize(json_decode(http_get($userinfoUrl)));
    if(preg_match('/\?/',$state)){
        header('Location:'.$state.'&u='.$userinfo);
    }else{
        header('Location:'.$state.'?u='.$userinfo);
    }
}